package agentV1

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"hc_server/pkg/app"
	"hc_server/pkg/file"
	"hc_server/pkg/setting"
	"hc_server/routers/api"
	"hc_server/routers/service/agentService"
	"hc_server/runtime/e"
)

// MyInfo 我的页面接口
func MyInfo(c *gin.Context) {
	appG := app.Gin{C: c}

	userId, _ := c.Get("userId")

	agent := agentService.Agent{Id: cast.ToInt(userId)}
	result, err := agent.AgentMyInfo()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("成功", result)
}

// MyCenterInfo 个人中心
func MyCenterInfo(c *gin.Context) {
	appG := app.Gin{C: c}

	userId, _ := c.Get("userId")

	agent := agentService.Agent{Id: cast.ToInt(userId)}
	result, err := agent.MyCenterInfo()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("成功", result)
}

// MyUploadAvatar 我的上传头像
func MyUploadAvatar(c *gin.Context) {
	appG := app.Gin{C: c}

	userId, _ := c.Get("userId")

	avatar, err := api.VerifyFileAndSave(c, "avatar", file.GetRandomFileName(), setting.GetConfig().App.AgentPath+cast.ToString(userId))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	agent := agentService.Agent{Id: cast.ToInt(userId), Avatar: avatar}
	err = agent.AgentUploadAvatar()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("成功", nil)
}

type MyPasswordEditParam struct {
	Opwd string `json:"opwd"` //旧密码
	Npwd string `json:"npwd"` //新密码
}

func MyPasswordEdit(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MyPasswordEditParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userId, _ := c.Get("userId")

	agent := agentService.Agent{Id: cast.ToInt(userId), Password: param.Opwd, NPassword: param.Npwd}
	err := agent.AgentMyPasswordEdit()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("成功", nil)
}

func MyInfoDelete(c *gin.Context) {
	appG := app.Gin{C: c}

	userId, _ := c.Get("userId")

	agent := agentService.Agent{Id: cast.ToInt(userId)}
	err := agent.AgentMyInfoDelete()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("成功", nil)
}
